package com.example.homeworkmanagement.utils;

import com.example.homeworkmanagement.pojo.Attachments;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Date;
import java.util.List;

public class DocxUtil {

    /**
     * 将上传的DOCX文件转换为附件实体
     */
    public static Attachments convertToAttachment(MultipartFile file) throws IOException {
        Attachments attachment = new Attachments();
        attachment.setFilename(file.getOriginalFilename());
        attachment.setCreatedAt(new Date());

        try (InputStream is = file.getInputStream();
             XWPFDocument document = new XWPFDocument(is)) {

            StringBuilder contentBuilder = new StringBuilder();
            List<XWPFParagraph> paragraphs = document.getParagraphs();
            for (XWPFParagraph paragraph : paragraphs) {
                contentBuilder.append(paragraph.getText()).append("\n");
            }

            attachment.setContent(contentBuilder.toString());
        }
        return attachment;
    }

    /**
     * 根据文本内容生成DOCX文件并保存到指定路径
     */
    public static void generateDocx(String filename, String content) throws IOException {
        // 获取C盘下载目录
        Path downloadDir = Paths.get(System.getProperty("user.home"), "Downloads");
        // 确保目录存在
        Files.createDirectories(downloadDir);

        // 构建完整文件路径
        Path filePath = downloadDir.resolve(ensureDocxExtension(filename));

        try (XWPFDocument document = new XWPFDocument();
             FileOutputStream fos = new FileOutputStream(filePath.toFile())) {

            // 按行分割内容并创建段落
            String[] lines = content.split("\n");
            for (String line : lines) {
                XWPFParagraph paragraph = document.createParagraph();
                paragraph.createRun().setText(line);
            }

            // 写入文件
            document.write(fos);
        }
    }

    /**
     * 确保文件名有.docx扩展名
     */
    public static String ensureDocxExtension(String filename) {
        if (!filename.toLowerCase().endsWith(".docx")) {
            return filename + ".docx";
        }
        return filename;
    }

    /**
     * 创建模拟的DOCX文件
     */
    public static MultipartFile createMockDocxFile(String content, String filename) throws IOException {
        // 创建DOCX文档
        XWPFDocument document = new XWPFDocument();
        XWPFParagraph paragraph = document.createParagraph();
        XWPFRun run = paragraph.createRun();
        run.setText(content);

        // 将文档写入字节流
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        document.write(baos);
        byte[] docxBytes = baos.toByteArray();

        // 创建MockMultipartFile
        return new MockMultipartFile(
                "file",           // 参数名（对应表单中的name属性）
                filename,         // 文件名
                "application/vnd.openxmlformats-officedocument.wordprocessingml.document", // MIME类型
                docxBytes         // 文件内容
        );
    }
}